package com.brspace.qualitycontrol.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.brspace.qualitycontrol.entity.*;
import com.brspace.qualitycontrol.entity.Process;
import com.brspace.qualitycontrol.entity.vo.MonthNumVo;
import com.brspace.qualitycontrol.entity.vo.PaginationVo;
import com.brspace.qualitycontrol.entity.vo.PublishVo;
import com.brspace.qualitycontrol.entity.vo.TypeVo;
import com.brspace.qualitycontrol.mapper.*;
import com.brspace.qualitycontrol.service.PublishFileService;
import com.brspace.qualitycontrol.service.PublishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brspace.qualitycontrol.utils.EmptyUtil;
import com.brspace.qualitycontrol.utils.R;
import com.brspace.qualitycontrol.utils.WordUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 发文拟稿 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-04-02
 */
@Service
public class PublishServiceImpl extends ServiceImpl<PublishMapper, Publish> implements PublishService {
    @Resource
    private PublishMapper publishMapper;
    @Resource
    private PublishFileMapper publishFileMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ProcessNodeMapper processNodeMapper;
    @Resource
    private ProcessMapper processMapper;
    @Resource
    private NodeUserMapper nodeUserMapper;
    @Resource
    private ProcessRouterMapper processRouterMapper;
    @Resource
    private HandleMapper handleMapper;



    /**
     * 新建发文
     * @param publish
     * @return
     */
    @Override
    @Transactional
    public R addPub(Publish publish) {
        if (EmptyUtil.isEmpty(publish.getNoticePeople())) {
            throw new SecurityException("核稿为空！");
        }
        if (EmptyUtil.isEmpty(publish.getOrganizer())) {
            throw new SecurityException("主办单位为空！");
        }
        if (baseMapper.selectOne(new QueryWrapper<Publish>().orderByDesc("number").last("limit 1")) != null) {
            publish.setNumber(baseMapper.selectOne(new QueryWrapper<Publish>().orderByDesc("number").last("limit 1")).getNumber() + 1);
        } else {
            String[] strNow1 = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).split("-");
            publish.setNumber(Long.parseLong("330122" + strNow1[0] + strNow1[1] + strNow1[2] + "001"));
        }
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        publish.setNodeId(processNodeMapper.selectOne(new QueryWrapper<ProcessNode>().eq("p_id",processMapper.selectOne(new QueryWrapper<Process>().eq("flow_name","发文")).getId()).eq("sort_num","1")).getId());
        publish.setProgress("同意");
        int pId = processNodeMapper.selectOne(new QueryWrapper<ProcessNode>().eq("p_id", processMapper.selectOne(new QueryWrapper<Process>().eq("flow_name", "发文")).getId()).eq("sort_num", "1")).getPId();
        Handle handle = new Handle();
        handle.setPId(pId);
        handle.setMiddlemanId(publish.getNoticePeopleId());

        if (publishMapper.insert(publish)>0) {
            Handle handle1 = new Handle();
            handle1.setDocumentId(publish.getId());
            handle1.setPId(pId);
            handle1.setHandleId(publish.getDraftUserId());
            handleMapper.insert(handle1);
            handle.setDocumentId(publish.getId());
            handleMapper.insert(handle);
            Map<String,Object> map = new HashMap<>();
            map.put("id",publish.getId());
            map.put("organizer",publish.getOrganizer());
            map.put("draftUser",publish.getNoticePeople());
            String fileId = null;
            try {
                fileId = WordUtils.exportMillCertificateWord(map, "发文", "static/post.ftl", publish.getDraftUserId());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return R.ok().message("成功！").data("fileId",fileId);
        }
        return R.error().message("失败！");
    }

    /**
     * 发文列表
     * @param pageParam
     * @param publishVo
     * @return
     */
    @Override
    public IPage<Publish> selectPage(Page<Publish> pageParam, PublishVo publishVo,String userId) {
        QueryWrapper<Publish> queryWrapper = new QueryWrapper<>();
        if (publishVo==null) {
            return baseMapper.selectPage(pageParam,new QueryWrapper<Publish>().eq("notice_people_id",userId).or().eq("issue_id",userId).or().eq("content_id",userId));
        }
        String number = publishVo.getWordNumber();
        String seal1 = publishVo.getSealBegin();
        String seal2 = publishVo.getSealEnd();
        String title = publishVo.getTitle();
        String state = publishVo.getState();
        if (!EmptyUtil.isEmpty(title)) {
            queryWrapper.like("title",title);
        }
        if (!EmptyUtil.isEmpty(state)) {
            queryWrapper.likeRight("state",state);
        }
        if (!EmptyUtil.isEmpty(number)) {
            queryWrapper.like("word_number",number);
        }
        if (!EmptyUtil.isEmpty(seal1)) {
            queryWrapper.ge("seal",seal1);
        }
        if (!EmptyUtil.isEmpty(seal2)) {
            queryWrapper.le("seal",seal2);
        }
        return baseMapper.selectPage(pageParam,queryWrapper.eq("notice_people_id",userId).or().eq("issue_id",userId).or().eq("content_id",userId));
    }

    //分页查询当前用户未阅发文列表
    @Override
    public PaginationVo<Publish> getPostList(Integer pageNum, Integer pageSize, String userId, int i) {
        PaginationVo<Publish> vo = new PaginationVo<>();
        //pageNum:查询的页数，pageSize:一页显示的数量
        PageHelper.startPage(pageNum,pageSize);
        List<Publish> consumerList = publishMapper.getPostList(userId,i);
        //获取总记录数pageInfo.getTotal()
        PageInfo<Publish> pageInfo = new PageInfo<>(consumerList);
        vo.setTotal(Integer.parseInt(String.valueOf(pageInfo.getTotal())));
        vo.setDataList(consumerList);
        return vo;
    }

    //每月统计发文数量
    @Override
    public List<MonthNumVo> statisticsByMonth() {
        return publishMapper.statisticsByMonth();
    }

    //计算今年发文数量和去年发文数量
    @Override
    public R getNowAndLastNum() {
        R r = new R();
        //计算今年的发文数量
        Integer nowNum = publishMapper.getNowNum();
        //计算去年的发文数量
        Integer lastNum = publishMapper.getLastNum();
        return r.data("now",nowNum).data("last",lastNum);
    }

    //发文类型统计列表
    @Override
    public R getTypeNumList() {
        List<TypeVo> list = publishMapper.getTypeNumList();
        return R.ok().data("list",list);
    }

    //保存文件并返回数据
    @Override
    public R savePublish(HttpServletRequest request, HttpServletResponse response, Publish publish) {
        if (EmptyUtil.isEmpty(publish.getIssue())) {
            throw new SecurityException("签发为空！");
        }
        if (EmptyUtil.isEmpty(publish.getNoticePeople())) {
            throw new SecurityException("核稿为空！");
        }
        if (EmptyUtil.isEmpty(publish.getOrganizer())) {
            throw new SecurityException("主办单位为空！");
        }
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        long id = snowflake.nextId();
        publish.setWordNumber(String.valueOf(id));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (publishMapper.insert(publish)>0) {
            for (PublishFile p: publish.getAnnex()) {
                p.setFileType(0);
                p.setPId(publish.getId());
                publishFileMapper.insert(p);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id",publish.getId());
            map.put("issue",publish.getIssue());
            map.put("content",publish.getContent() == null ? "" : publish.getContent());
            map.put("noticePeople",publish.getNoticePeople());
            map.put("organizer",publish.getOrganizer());
            map.put("draftUser",publish.getDraftUser());
            map.put("draftMatter",publish.getDraftMatter());
            map.put("giveOffice",publish.getGiveOffice());
            map.put("copyOffice",publish.getCopyOffice());
            map.put("typing",publish.getTyping() == null ? "" : publish.getTyping());
            map.put("examine",publish.getExamine() == null ? "" : publish.getExamine());
            map.put("dayin",publish.getDayin() == null ? "" : publish.getDayin());
            map.put("wordNumber",String.valueOf(id));
            map.put("seal",publish.getSeal() == null ? "" :  sdf.format(publish.getSeal()));
            try {
                WordUtils.exportMillCertificateWord(request,response,map,publish.getWordNumber(),"static/post.ftl");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return R.ok().data("rows",String.valueOf(id));
        }
        return R.error();
    }

    /**
     * 发文流程运转
     *@author Hugo
     *@date 2021-04-23 09:45
     **/
    @Override
    public String examine(Publish publish,String nextId,String userId) {
        if (nextId == "undefined"){
            throw new SecurityException("请选择流转的人员");
        }
        if (publish.getNodeId()==0){
            throw new SecurityException("流程已经结束");
        }
        if (  processNodeMapper.selectById(publish.getNodeId()).getSortNum() == 0){
            publish.setProgress("同意");
        }
        String deptId = userMapper.selectById(userId).getDeptId();

        if ( userMapper.selectList(new QueryWrapper<User>().eq("dept_id", deptId).eq("role", "文书")).size() == 0){
            throw new SecurityException("该部门下还未分配文书 请分配文书");
        }
        publish.setSortNumber( processNodeMapper.selectById(publish.getNodeId()).getSortNum());
        String role = userMapper.selectOne(new QueryWrapper<User>().eq("dept_id", userMapper.selectById(userId).getDeptId()).eq("role", "文书")).getRole();
        Integer maxNum = processNodeMapper.sortMax(processNodeMapper.selectOne(new QueryWrapper<ProcessNode>().eq("id", publish.getNodeId())).getPId());
        int pId = processRouterMapper.selectOne(new QueryWrapper<ProcessRouter>().eq("current_id", publish.getNodeId()).eq("requirement", publish.getProgress())).getPId();
        int a = processRouterMapper.selectOne(new QueryWrapper<ProcessRouter>().eq("requirement",publish.getProgress()).eq("current_id",publish.getNodeId())).getTargetId();
        if (processNodeMapper.selectById(a).getSortNum().equals(maxNum)){
            publish.setNodeId(0);
        }else {
            publish.setNodeId(a);
        }
        // 更改上一个节点 代办和已办
        Map<String , Object> map = new HashMap<>(16);
        map.put("document_id",publish.getId());
        map.put("middleman_id",userId);
        if (handleMapper.selectCount(new QueryWrapper<Handle>().allEq(map))>0){
            Handle handle = handleMapper.selectOne(new QueryWrapper<Handle>().allEq(map));
            handle.setHandleId(userId);
            handle.setMiddlemanId("");
            handleMapper.updateById(handle);
        }
        // 插入下一事项办理人代办和已办
        Handle handle = new Handle();
        handle.setPId(pId);
        handle.setDocumentId(publish.getId());
        handle.setMiddlemanId(nextId);
        handle.setNId(a);
        handleMapper.insert(handle);
        baseMapper.updateById(publish);
        return role;
    }

    /**
     *分页查询代办事项
     *@author Hugo
     *@date 2021-04-26 15:03
     **/
    @Override
    public List<Publish> pageList(int page, int limit, String userId) {
        int pId = processMapper.selectOne(new QueryWrapper<Process>().eq("flow_name", "发文")).getId();
        List<Handle> handles = handleMapper.selectList(new QueryWrapper<Handle>().eq("middleman_id", userId).eq("p_id", pId));
        List<Publish> publishes = new ArrayList<>();
        for (Handle handle : handles) {
            System.out.println(handle.getDocumentId());
            publishes.add(publishMapper.selectById(handle.getDocumentId()));
        }
        List<Publish> currentPageList = new ArrayList<>();
        if (publishes != null && publishes.size() > 0) {
            int currIdx = (page > 1 ? (page - 1) * limit : 0);
            for (int i = 0; i < limit && i < publishes.size() - currIdx; i++) {
                currentPageList.add(publishes.get(currIdx + i));
            }
        }
        return currentPageList;
    }

    /**
     *分页查询已办事项
     *@author Hugo
     *@date 2021-04-28 11:39
     **/
    @Override
    public List<Publish> pageCompleteList(int page, int limit, String userId) {
        int pId = processMapper.selectOne(new QueryWrapper<Process>().eq("flow_name", "发文")).getId();
        List<Handle> handles = handleMapper.selectList(new QueryWrapper<Handle>().eq("handle_id", userId).eq("p_id", pId));
        List<Publish> publishes = new ArrayList<>();
        for (Handle handle : handles) {

                publishes.add(publishMapper.selectById(handle.getDocumentId()));

        }
        List<Publish> currentPageList = new ArrayList<>();
        if (publishes != null && publishes.size() > 0) {
            int currIdx = (page > 1 ? (page - 1) * limit : 0);
            for (int i = 0; i < limit && i < publishes.size() - currIdx; i++) {
                currentPageList.add(publishes.get(currIdx + i));
            }
        }
        return currentPageList;
    }

    /**
     *分页查询所有
     *@author Hugo
     *@date 2021-04-28 11:39
     **/
    @Override
    public List<Publish> pageAllList(int page, int limit, String userId) {
        int pId = processMapper.selectOne(new QueryWrapper<Process>().eq("flow_name", "发文")).getId();
        List<Handle> handles = handleMapper.selectList(new QueryWrapper<Handle>().eq("handle_id", userId).eq("p_id", pId).or().eq("middleman_id",userId).eq("p_id", pId));
        List<Publish> publishes = new ArrayList<>();
        for (Handle handle : handles) {
            publishes.add(publishMapper.selectById(handle.getDocumentId()));
        }
        List<Publish> currentPageList = new ArrayList<>();
        if (publishes != null && publishes.size() > 0) {
            int currIdx = (page > 1 ? (page - 1) * limit : 0);
            for (int i = 0; i < limit && i < publishes.size() - currIdx; i++) {
                currentPageList.add(publishes.get(currIdx + i));
            }
        }
        return currentPageList;
    }


}
